<?php
namespace app\index\controller;

use app\index\model\LoginListModel;
use app\index\model\LoginTokenModel;
use app\index\model\UserModel;
use app\index\model\UserRoleModel;
use app\index\service\EncryptService;
use app\index\service\MessageService;
use think\Db;
use think\Exception;
use think\Request;
use app\index\service\LoginService;

class Login extends Access
{
    public function login(Request $request)
    {
        $param = getDecryptData($request->post());
        $result = $this->validate($param,'Login.login_pass');

        if($this->validate($param,'Login.login_pass') !== true){
            return outputJson(4009,$result);
        }

        $param['ip'] = $request->ip();
        $param['type'] = isset($param['type']) ? $param['type'] : 1;
        try{
            $user = (new LoginService())->login_by_pass($param);
        }catch (\Exception $e) {
            return outputJson(4000, $e->getMessage());
        }

        $roleidArr = UserRoleModel::where('id','in',$user['roleid'])->group('type')->column('type');


        if(count($roleidArr) < 1){
            return outputJson(4000, '登录失败');
        }elseif(count($roleidArr) == 1){
            $tokenHour = 10;
            if(isset($param['keep']) && $param['keep'] == 1){
                $tokenHour = 7*24;
            }
            $token = create_random_str($user['id']);
            if(!LoginTokenModel::add_token($user['id'], $roleidArr[0], $token, $param['ip'], $user['comid'], $param['type'], 1, $tokenHour)){
                return outputJson(4000, '登录失败');
            }
            LoginListModel::add_row($user,$param['ip'],$param['type'],1);
            $tokenStr = str_replace('/','&&++&&', (new EncryptService())->dataEncrypt($token));

            return outputJson(2000, '登录成功', ['succ'=>1, 'token'=>$tokenStr]);
        }else{
            $returnArr = [];
            foreach ($roleidArr as $v){
                if($v == 1){
                    $returnArr[] = ['value'=>1, 'name'=>'公司人员'];
                }
                if($v == 2){
                    $returnArr[] = ['value'=>2, 'name'=>'项目人员'];
                }
                if($v == 3){
                    $returnArr[] = ['value'=>3, 'name'=>'项目联营人'];
                }
                if($v == 4){
                    $returnArr[] = ['value'=>4, 'name'=>'供应商'];
                }
                if($v == 5){
                    $returnArr[] = ['value'=>5, 'name'=>'分公司人员'];
                }
            }
            return outputJson(2000, '登录成功', ['succ'=>0, 'rolearr'=>$returnArr]);
        }
    }
    public function loginrole(Request $request)
    {
        $param = getDecryptData($request->post());
        $result = $this->validate($param,'Login.login_pass');

        if($this->validate($param,'Login.login_pass') !== true){
            return outputJson(4009,$result);
        }

        $param['ip'] = $request->ip();
        $param['type'] = isset($param['type']) ? $param['type'] : 1;
        try{
            $user = (new LoginService())->login_by_pass($param);
        }catch (\Exception $e) {
            return outputJson(4000, $e->getMessage());
        }

        $roleidArr = UserRoleModel::where('id','in',$user['roleid'])->group('type')->column('type');
        if(!in_array($param['roletype'], $roleidArr)){
            return outputJson(4000, '登录失败');
        }

        $tokenHour = 10;
        if(isset($param['keep']) && $param['keep'] == 1){
            $tokenHour = 7*24;
        }
        $token = create_random_str($user['id']);
        if(!LoginTokenModel::add_token($user['id'], $param['roletype'], $token, $param['ip'], $user['comid'], $param['type'], 1, $tokenHour)){
            return outputJson(4000, '登录失败');
        }
        LoginListModel::add_row($user,$param['ip'],$param['type'],1);
        $tokenStr = str_replace('/','&&++&&', (new EncryptService())->dataEncrypt($token));
        return outputJson(2000, '登录成功', $tokenStr);
    }


    public function loginapp(Request $request)
    {
        $param = $request->post();
        $result = $this->validate($param,'Login.login_pass');
        if($this->validate($param,'Login.login_pass') !== true){
            return outputJson(4009,$result);
        }

        $param['ip'] = $request->ip();
        $param['type'] = isset($param['type']) ? $param['type'] : 1;
        try{
            $user = (new LoginService())->login_by_app($param);
        }catch (\Exception $e) {
            return outputJson(4000, $e->getMessage());
        }

        $roleidArr = UserRoleModel::where('id','in',$user['roleid'])->group('type')->column('type');


        if(count($roleidArr) < 1){
            return outputJson(4000, '登录失败');
        }elseif(count($roleidArr) == 1){
            $tokenHour = 365*24;
            $token = create_random_str($user['id']);
            if(!LoginTokenModel::add_token($user['id'], $roleidArr[0], $token, $param['ip'], $user['comid'], $param['type'], 1, $tokenHour)){
                return outputJson(4000, '登录失败');
            }
            LoginListModel::add_row($user,$param['ip'],$param['type'],1);
            $tokenStr = str_replace('/','&&++&&', (new EncryptService())->dataEncrypt($token));

            return outputJson(2000, '登录成功', ['succ'=>1, 'token'=>$tokenStr]);
        }else{
            $returnArr = [];
            foreach ($roleidArr as $v){
                if($v == 1){
                    $returnArr[] = ['value'=>1, 'name'=>'公司人员'];
                }
                if($v == 2){
                    $returnArr[] = ['value'=>2, 'name'=>'项目人员'];
                }
                if($v == 3){
                    $returnArr[] = ['value'=>3, 'name'=>'项目联营人'];
                }
                if($v == 4){
                    $returnArr[] = ['value'=>4, 'name'=>'供应商'];
                }
                if($v == 5){
                    $returnArr[] = ['value'=>5, 'name'=>'分公司人员'];
                }
            }
            return outputJson(2000, '登录成功', ['succ'=>0, 'rolearr'=>$returnArr]);
        }
    }
    public function loginapprole(Request $request)
    {
        $param = $request->post();
        $result = $this->validate($param,'Login.login_pass');

        if($this->validate($param,'Login.login_pass') !== true){
            return outputJson(4009,$result);
        }

        $param['ip'] = $request->ip();
        $param['type'] = isset($param['type']) ? $param['type'] : 1;
        try{
            $user = (new LoginService())->login_by_pass($param);
        }catch (\Exception $e) {
            return outputJson(4000, $e->getMessage());
        }

        $roleidArr = UserRoleModel::where('id','in',$user['roleid'])->group('type')->column('type');
        if(!in_array($param['roletype'], $roleidArr)){
            return outputJson(4000, '登录失败');
        }

        $tokenHour = 365*24;
        $token = create_random_str($user['id']);
        if(!LoginTokenModel::add_token($user['id'], $param['roletype'], $token, $param['ip'], $user['comid'], $param['type'], 1, $tokenHour)){
            return outputJson(4000, '登录失败');
        }
        LoginListModel::add_row($user,$param['ip'],$param['type'],1);
        $tokenStr = str_replace('/','&&++&&', (new EncryptService())->dataEncrypt($token));
        return outputJson(2000, '登录成功', $tokenStr);
    }

    public function reg(Request $request)
    {
        $param = $request->post();
        $result = $this->validate($param,'Login.reg');
        if($result !== true){
            return outputJson(4009,$result);
        }
        if(UserModel::get_info_by_tel($param['tel'])){
            return outputJson(4009, "该手机号码用户已存在，请直接登录或联系客服人员");
        }

        if(!(new MessageService())->check_code($param['tel'], $param['code'])){
            return outputJson(4009, "验证码错误");
        }

        $vision = isset($param['vision']) ? $param['vision'] : '';
        unset($param['vision']);

        unset($param['token']);
        unset($param['code']);
        $param['reg_pass'] = $param['pass'];
        $param['pass'] = md5(md5($param['pass']));

        if($vision == 'wisecert'){
            $param['comid'] = 1;
            $param['deptid'] = 2;
            $param['gangid'] = 6;
            $param['roleid'] = 25;
        }else{
            $param['comid'] = 1;
            $param['deptid'] = 34;
            $param['gangid'] = 1;
            $param['roleid'] = 24;
        }

        $param['realname'] = $param['reg_name'];
        $param['created_at'] = date('Y-m-d H:i:s');
        $param['isreg'] = 1;
        $param['reg_tel'] = $param['tel'];
        $param['reg_ip'] = $request->ip();
        $param['reg_enddt'] = date("Y-m-d H:i:s", time()+15*24*3600);
        $param['reg_vision'] = $vision;

        Db::startTrans();
        try{
            $userid = UserModel::insertGetId($param);

            $tokenHour = 10;
            $token = create_random_str($userid);
            if(!LoginTokenModel::add_token($userid, 1, $token, $param['reg_ip'], $param['comid'], 1, 1, $tokenHour)){
                return outputJson(4000, '登录失败');
            }
            $userInfo = UserModel::where(['id'=>$userid])->find();
            LoginListModel::add_row($userInfo,$param['reg_ip'],1,1);
            $tokenStr = str_replace('/','&&++&&', (new EncryptService())->dataEncrypt($token));
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000, '登录成功', ['token'=>$tokenStr]);
    }

}
